/**
 * 路由文件
 */
 const vipLogin = require("../assets/vip_login.json");
 const conn = require("./conn.js");
 
//1、导入express框架
var express = require('express')
//2、使用框架中的router容器
var router = express.Router()

const fs = require('fs')
const path = require('path')
//上传图片的模板
var multer = require('multer');
//生成的图片放入uploads文件夹下
var upload = multer({ dest: '../src/assets/uploads' })
// 
const baseConfig = require("../utils/baseConfig");
const jwt = require('jsonwebtoken')
 
 // 输出json
router.get("/login", (req, res) => {
    //在这里做点什么
    res.send(vipLogin)
}) 
 
const _SQL= require('./common')
// 中台模块
const API="/api/admin"

/*
req.query用来获取get方法传递的参数
req.body用来获取post方法传递的参数
*/ 
/*******************************************登录********************************************/
router.post(API+'/loginin', (req, res) => {
    let sql = "select id from user where username = ? and password = ?";
    if (req.body.username=='' || req.body.password=='' ) {
        res.send({ code:0,msg:'请输入用户名或密码',data:'req'})
        return
    }
    console.log(req.body,"ewq")
    let data = [req.body.username,req.body.password]
    conn.query(sql,data,(err,result)=>{
        if (err) {
            res.send({ code:0,msg:err,data:'err'})
        }else{
            if(result.length==0){
               return res.send({ code:0,msg:'用户名或密码不正确',data:'err'})
            }
            var id=result[0].id
            var tokenStr = baseConfig.setToken(id)
            res.send({
                code: 200,
                msg: '登录成功',
                data: {
                    token:tokenStr
                }
            })  
        }
    })       
}) 
//注册
router.post(API+"/adduser", (req, res) => {  
    let sql = "select id from user where username = ?";
    if (req.query.username=='' || req.query.password=='' ) {
        res.send({ code:0,msg:'请输入用户名或密码',data:'req'})
        return
    }
    let data = [req.query.username]
    conn.query(sql,data,(err,result)=>{
        if (err) {
            res.send({ code:0,msg:err,data:'err'})
        }else{
            if(result.length==0){
               return res.send({ code:0,msg:'用户名已存在',data:'err'})
            }
            let insertSql = `insert into user VALUES(null,?,?,?)`;
            let datas = [req.query.username,req.query.password,new Date()]
            conn.query(insertSql, datas,function (error, results) {
                if (error) {
                    res.send({ code:0,msg:error,data:null})
                    return false
                }else{
                    res.send({ code:200,msg:'OK',data:null})
                }
            });
        }
    })
       
});
//修改密码
router.post(API+"/updateuser", (req, res) => {
    if (req.query.password) {
        let updateSql =`update user set password = ?,time = ? where id = ?`;
        let id=baseConfig.getToken(req.headers.authorization)
        let data = [reqreq.query.password,new Date(),id]
        conn.query(updateSql, data,function (error, results) {
            if (error) {
                res.send({ code:0,msg:error,data:null})
                return false
            }else{
                // changedRows改变行数为0说明没有内容更新
                if (results.changedRows==0) {
                    res.send({ code:0,msg:results,data:null})
                    return false
                }
                res.send({ code:200,msg:'修改密码成功',data:null})
            }
        });
    }else{
        res.send({ code:0,msg:'密码必填',data:null})
    }    
}); 
//查询个人信息
router.get(API+'/getuserinfo', function(req, res) {
    console.log(req.headers)
    var id=''
    if (baseConfig.getToken(req.headers.authorization)) {
         id=baseConfig.getToken(req.headers.authorization)
         console.log(id,"id")
    }
    let sql =   `select * from news where id = ?`;
    let data = [id]
    conn.query(sql,data,(err,result)=>{
        if (err) {
            return res.send({ code:1,msg:'OK',data:err})
        }
        res.send({ code:1,msg:'OK',data:result[0]})
    })
})
/*******************************************新闻********************************************/
//创建新闻
router.post(API+"/addnews", (req, res) => {  
    var reqdata=req.body
    if (!reqdata.title) {
         res.send({ code:0,msg:'请输入标题',data:''})
        return
    }
    if ( !reqdata.txt) {
         res.send({ code:0,msg:'请输入内容',data:''})
        return
    }
    // let insertSql = `insert into user VALUES(null,?,?,?)`;
    // let datas = [reqdata.title,reqdata.img,reqdata.txt]
    let insertSql = `insert into news set ?`;
    let datas =reqdata
    conn.query(insertSql, datas,function (error, results) {
        if (error) {
            res.send({ code:0,msg:error,data:11})
            return false
        }else{
            res.send({ code:200,msg:'OK',data:22})
        }
    });
      
});
//新闻列表
router.get(API+'/getnewslist', function(req, res) {

    var pageNum=req.query.pageNum ? Number(req.query.pageNum)  : 1
    var pageSize= req.query.pageSize  ? Number(req.query.pageSize) : 10
    var reqdata={
        star:(pageNum- 1 ) * pageSize ,
        end :  pageSize * pageNum,
    }
    let sql = "select * from news ORDER BY id DESC limit ? , ?";
    let data=[reqdata.star,reqdata.end]
    let lensql="SELECT COUNT(*) as count FROM news;"
    conn.query(lensql,data,(errs,results)=>{
        if (errs) {
            return res.send({ code:0,msg:errs,data:'err'})
        }
        conn.query(sql,data,(err,result)=>{
            if (err) {
                return res.send({ code:0,msg:err,data:'err'})
            }
            res.send({ code:200,msg:'OK',data:{
                list:result,
                count:results[0].count,
                ...reqdata
            }})
        })
         
    })

})
//查询新闻详情
router.get(API+'/getnewsinfo', function(req, res) { 
    let sql =   `select * from news where id = ?`;
    let data = [req.query.id]
    conn.query(sql,data,(err,result)=>{
        if (err) {
            return res.send({ code:0,msg:err,data:''})
        }
        res.send({ code:200,msg:'OK',data:result[0]})
    })
})
//删除新闻
router.post(API+"/deletenews", (req, res) => {
    if (req.body.id) {
        let deleteSql =`delete from news where id = ?`;
        let data = [req.body.id]
        conn.query(deleteSql, data,function (error, results) {
            if (error) {
                res.send({ code:0,msg:error,data:null})
                return false
            }else{
                // affectedRows是受影响的行数
                if (results.affectedRows==0) {
                    res.send({ code:0,msg:results,data:null})
                    return false
                }
                res.send({ code:200,msg:'OK',data:null})
            }
        });
    }else{
        res.send({ code:0,msg:'参数必填',data:null})
    }    
}); 
//修改新闻
router.post(API+"/updatenews", (req, res) => {  
    if (req.body.id) {
        let updateSql =`update news set ? where id = ?`;
        let data = [req.body,req.body.id]
        conn.query(updateSql, data,function (error, results) {
            if (error) {
                res.send({ code:0,msg:error,data:null})
                return false
            }else{
                // changedRows改变行数为0说明没有内容更新
                if (results.affectedRows==0) {
                    res.send({ code:0,msg:results,data:results})
                    return false
                }
                res.send({ code:200,msg:'修改成功',data:results})
            }
        });
    }else{
        res.send({ code:0,msg:'id必填',data:null})
    }    
});
/*******************************************案例********************************************/
//新闻列表
router.get(API+'/getcaselist', function(req, res) {
    _SQL.findlist(req,res,'cases')
})
//创建案例
router.post(API+"/addcase", (req, res) => {  
    var reqdata=req.body
    if (!reqdata.title) {
         res.send({ code:0,msg:'请输入标题',data:''})
        return
    }
    if ( !reqdata.txt) {
         res.send({ code:0,msg:'请输入内容',data:''})
        return
    }
    if ( !reqdata.tip) {
        res.send({ code:0,msg:'请输入标签',data:''})
       return
   }
   _SQL.insertData(req,res,'cases') 
      
});
//查询案例详情
router.get(API+'/getcaseinfo', function(req, res) { 
    _SQL.getDataInfoById(req,res,'cases')
})
//删除案例
router.post(API+"/deletecase", (req, res) => {
    if (req.body.id) {
        _SQL.deleteDataById(req,res,'cases')
    }else{
        res.send({ code:0,msg:'参数必填',data:null})
    }    
}); 
//修改案例
router.post(API+"/updatecase", (req, res) => {  
    if (req.body.id) {
        _SQL.updateById(req,res,'cases')
    }else{
        res.send({ code:0,msg:'id必填',data:null})
    }    
});
/*******************************************留言********************************************/
//留言列表
router.get(API+'/getcontentlist', function(req, res) {
    _SQL.findlist(req,res,'content')
})
//删除 
router.post(API+"/deletecontent", (req, res) => {
    if (req.body.id) {
        _SQL.deleteDataById(req,res,'content')
    }else{
        res.send({ code:0,msg:'参数必填',data:null})
    }    
}); 

/****************************************************************前台********************************************************/
//添加留言
const API2="/api/pc"
router.post(API2+"/addcontent", (req, res) => {  
    var reqdata=req.body
    console.log(req.query,req.body,req.params)
    if (!reqdata.real_name) {
         res.send({ code:0,msg:'请输入姓名',data:''})
        return
    }
    if ( !reqdata.phone) {
         res.send({ code:0,msg:'请输入手机号',data:''})
        return
    }
    if ( !reqdata.email) {
        res.send({ code:0,msg:'请输入邮箱',data:''})
       return
   } 
   if ( !reqdata.content) {
        res.send({ code:0,msg:'请输入留言内容',data:''})
    return
    }
    var reqbody={
        real_name:reqdata.real_name,
        phone:reqdata.phone,
        email:reqdata.email,
        content:reqdata.content,
        cooperation:reqdata.cooperation
    }
    req.body=reqbody
   _SQL.insertData(req,res,'content') 
      
});

//案例列表
router.get(API2+'/getcaselist', function(req, res) {
    _SQL.findlist(req,res,'cases')
})
//案例详情
router.get(API2+'/getcaseinfo', function(req, res) {
    _SQL.getDataInfoById(req,res,'cases')
})
//新闻列表
router.get(API2+'/getnewslist', function(req, res) {
    _SQL.findlist(req,res,'news')
})
//新闻详情
router.get(API2+'/getnewsinfo', function(req, res) {
    _SQL.getDataInfoById(req,res,'news')
})
//上传图片
router.post('/uploadsimg', upload.single('file'), (req, res) => {
    console.log(req.file);
    /*
    {
        fieldname: 'file',
        originalname: '微信图片_20220925215734.png',
        encoding: '7bit',
        mimetype: 'image/png',
        destination: '../src/assets/uploads',
        filename: 'c877c11ed1ff0394c0a2a425ed8b6532',
        path: '..\\src\\assets\\uploads\\c877c11ed1ff0394c0a2a425ed8b6532',
        size: 1262982
        }
        res.send('ok')
    */
    const isJPG = req.file.mimetype === 'image/jpeg' || req.file.mimetype === 'image/jpg' ||  req.file.mimetype === 'image/png'
    if (!isJPG) {
        return res.send({ code:0,msg:"图片只能是 jpeg / png / jpg 格式!",data:null})
    }
    var maxsize=5 * 1024 * 1024;//图片最大为5M
    if (req.file.size>maxsize) {
        return res.send({ code:0,msg:"图片最大为5M",data:null})
    }  
    //读取路径（req.file.path）
    fs.readFile(req.file.path, (err, data) => {
        //1.1、读取失败，说明没有上传成功
        // console.log(req.file.path);
        if (err) { return res.send('上传失败') }
        // console.log(data);
        //1.2、读取成功
        //声明图片名字为时间戳和随机数拼接成的，尽量确保唯一性
        let time = Date.now() + parseInt(Math.random() * 999) + parseInt(Math.random() * 2222);
        //拓展名(后缀)
        let extname = req.file.mimetype.split('/')[1]
        //拼接成图片名
        let keepname = time + '.' + extname

        //2、开始写入 
        fs.writeFile(path.join(__dirname, '../assets/uploads/'  +keepname), data, (err) => {
            
            if (err) { return res.send('写入失败') }
            res.send({
                code:200,
                msg:'上传ok',
                data:'http://127.0.0.1:3300/uploads/'  +keepname
            })
        })
    })
})
 
module.exports = router
